﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.回氦)]
    public class BackHelium : ServierBase
    {
        private volatile int _ngRearGlueNail = 0, _total = 0;
        public BackHelium(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporary, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporary, homeStatic, mesParameterStatic)
        {
            _interaction = new ProduceOpenAddInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
        }

        public override Task Handle(Context.DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                _ngRearGlueNail = _total = 0;
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_BackHelium, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");
                Parallel.ForEach(erinnerungen.Item2, battery =>
                {
                    Interlocked.Increment(ref _total);
                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                    if (entity == null)
                    {
                        RunLog($"-[{context.DeviceIndex}]-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{context.DeviceIndex}]-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                        WriteResult("", ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                        return;
                    }
                    #region 数据赋值
                    try
                    {
                        #region 回氦数据获取
                        BatteryBackHeliumDataModel batteryBackHelium = new BatteryBackHeliumDataModel();
                        plc.ReadClass($"PC_AdhesiveNailHeightDataUP[{battery.Index - 1}]", batteryBackHelium);
                        //plc.ReadClass($"PC_HeDataUP[{battery.Index - 1}]", batteryBackHelium);
                        RunLog($"接收到的数据：{System.Text.Json.JsonSerializer.Serialize(batteryBackHelium, GlobalStatic.Options)}");
                        #endregion
                        if (batteryBackHelium.AfterSealingResult != 1)
                        {
                            Interlocked.Increment(ref _ngRearGlueNail);
                        }
                        entity.HeliumBeforeVacuum = batteryBackHelium.HeliumBeforeVacuum;
                        entity.HeliumAfterVacuum = batteryBackHelium.HeliumAfterVacuum;
                        entity.HeliumStationNo = (byte)batteryBackHelium.HeliumStationNo;
                        entity.BackHeliumDuration = (byte)batteryBackHelium.HeliumTime;
                        entity.TimeBackHelium = dateTime.GetJSTimeUtc();
                        entity.AfterSealingResult = batteryBackHelium.AfterSealingResult == 1 ? ResultTypes.合格 : ResultTypes.密封塞NG;

                    }
                    catch (Exception ex)
                    {
                        RunLog($"-[{context.DeviceIndex}]-[{battery.Index}] 数据赋值 异常：{ex}");
                        WriteResult("", ResultTypes.不合格, plc, battery.Address_Struct, context);
                        return;
                    }
                    #endregion
                    try
                    {
                        entity.Update();
                    }
                    catch (Exception ex)
                    {
                        RunLog($"-[{battery.Index}] 数据库保存异常：{ex}");
                        WriteResult("", ResultTypes.不合格, plc, battery.Address_Struct, context);
                        return;
                    }

                    #region MES 出站
                    if (_parameterStatic.DecideParameter.EnableMES)
                    {
                        if (_systemConfig.SCM.OutputProcesses == OutputProcessesEnum.回氦)  //胶钵NG算OK
                        {
                            BatteryOutboundDataUpload(_interaction, entity);
                        }
                    }
                    #endregion

                    WriteResult(entity.BarCode, entity.ResultTotal, plc, battery.Address_Struct, context);
                    _homeStatic.AddOutBattery(entity);
                });

                _homeStatic.ChartData.Total_GlueNail += _total;//胶钉总数
                _homeStatic.ChartData.NG_RearGlueNail += _ngRearGlueNail;//胶钉NG数
                int sum = _homeStatic.ChartData.Total_GlueNail - _homeStatic.ChartData.NG_RearGlueNail;
                double c = (double)sum / _homeStatic.ChartData.Total_GlueNail;
                RunLog($"胶钉总数:{_homeStatic.ChartData.Total_GlueNail},胶钉NG数:{_homeStatic.ChartData.NG_RearGlueNail},胶钉合格率：{c}");
                _homeStatic.ChartData.GlueNailPassingRate = Math.Round(c, 4, MidpointRounding.ToNegativeInfinity) * 100;
            }
            catch (Exception ex)
            {
                RunLog($"-[{context.DeviceIndex}] 异常：{ex}");
            }
            return base.Handle(context);
        }
    }
}
